package com.ruoyi.common.utils.file;

import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import static org.springframework.util.FileCopyUtils.BUFFER_SIZE;

/**
 * @类名: ZipUtils
 * @描述:
 * @作者: liudf
 * @日期: 2021/8/1 13:15
 */
@Slf4j
public class ZipFileUtils {

    /**
     * 压缩成ZIP 方法 * @param srcFiles 需要压缩的文件列表
     * @param out 压缩文件输出流
     * @throws RuntimeException 压缩失败会抛出运行时异常
     */
    public static void toZip(List<String> srcFiles , OutputStream out){
        long start = System.currentTimeMillis();
        try (ZipOutputStream zos = new ZipOutputStream(out);) {
            for (String filePath : srcFiles) {
                File srcFile = new File(filePath);
                byte[] buf = new byte[BUFFER_SIZE];
                zos.putNextEntry(new ZipEntry(srcFile.getName()));
                int len;
                FileInputStream in = new FileInputStream(srcFile);
                while ((len = in.read(buf)) != -1){
                    zos.write(buf, 0, len);
                }
                zos.closeEntry();
                in.close();
            }
            long end = System.currentTimeMillis();
            log.info("压缩完成，耗时：" + (end - start) +" ms");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

//    public static void main(String[] args) throws FileNotFoundException {
//        ZipFileUtils zf = new ZipFileUtils();
//
//        List files = new ArrayList();
//
//        //确保下面文件存在
//
//        files.add("C:\\Users\\wangli\\Desktop\\1627791093383.pdf");
//        files.add("C:\\Users\\wangli\\Desktop\\创意作品征集实施说明.pdf");
//
//        zf.toZip(files,new FileOutputStream(new File("C:\\Users\\wangli\\Desktop\\test.zip")));
//
//    }

}
